package org.mogu;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.mogu.adapter.ChatListAdapter;
import org.mogu.control.inter.ReplayTextImg;
import org.mogu.control.model.IMUser;
import org.mogu.db.DBhelper;
import org.mogu.service.GetSyncUrl;
import org.mogu.service.InfoSync;
import org.mogu.staticvalue.Convert;
import org.mogu.tools.HeaderPic;
import org.mogu.tools.Imgtools;
import org.mogu.tools.UrlSync;



import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

public class ChatWindowsActivity extends ListActivity implements ReplayTextImg,View.OnClickListener,OnItemLongClickListener {
	public Handler mMainHandler,chatListHandler;
	private ChatListAdapter chatListAdapter=null;
	private ListView mListView;
	private IMUser imUser=null;
	private EditText say;
	private ImageView img;
	private ImageView headIcon;
	
	private UrlSync urlSync=new UrlSync();
	Intent intent;
	ChatWindowsActivity chatWindows;
	
	boolean isMyChat=true;
	
	int textPost=0;
	int changePost=0;
	
	String beforeStr=null;
	TextWatcher textW;
	boolean isW=false;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.qq_chatwindow);
		headIcon = (ImageView)findViewById(R.id.headIcon);
		say=(EditText)findViewById(R.id.umeng_analyse_editTxtFb);
		textW=new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
//				if(s!=null&&s.toString().length()>=0){
//					say.setSelection(start+s.length()-1);
//				}
//				changePost=s.length()-beforeStr.length();
//				s=Imgtools.getContent(s.toString());
				if(isW){
					return;
				}
//				if(s==null){
//					s="";
//				}
//				if(beforeStr==null){
//					beforeStr="";
//				}
				changePost=s.length()-beforeStr.length();
				if(changePost<0){
					changePost+=1;
				}
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
//				textPost=count;
				if(isW){
					return;
				}
				beforeStr=s.toString();
				textPost=start;
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if(isW){
					return;
				}
				isW=true;
					say.setText(Imgtools.getContent(say.getText().toString()));
					isW=false;
					try{
						say.setSelection(textPost+changePost);
					}catch(Exception e){
						say.setSelection(0);
					}
					
					Log.v("textPost", ""+textPost);
					Log.v("changePost", ""+changePost);
				
			}
		};
		say.addTextChangedListener(textW);
		img=(ImageView)findViewById(R.id.chat_emo_button);
		img.setOnClickListener(this);
		mListView=getListView();
		mListView.setOnItemLongClickListener(this);
		chatWindows=this;
		intent=this.getIntent(); 
        Bundle bunde = intent.getExtras();
        if(bunde!=null){
        	imUser=(IMUser)bunde.getSerializable("iMUser");
        }
        
        TextView title=(TextView)findViewById(R.id.user_title);
//        TextView desc=(TextView)findViewById(R.id.user_desc);
        if(imUser!=null){
        	title.setText(imUser.getUnicename());
        	try{
        		headIcon.setImageResource(HeaderPic.getHeader(imUser.getHeader()));
        	}catch(Exception e){
        		Log.e("没有头像", imUser.getUnicename());
        	}
        	
//            desc.setText(imUser.getDesc());
        }
        
//		code = bunde.getString("code");
		
		
		
		mMainHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				// // 接收子线程的消息
				if(msg.arg1==1){
					UrlSync urlSync=(UrlSync)msg.obj;
					if(imUser.getCode().equals(urlSync.getCode())){
						chatListAdapter.getData();
					}
					
				}
				
			}

		};
		chatListHandler=new Handler(){
			@Override
			public void handleMessage(Message msg) {

				// // 接收子线程的消息
				if(msg.arg1==1){
			        	chatListAdapter.getData();
				}else{
					mListView.setAdapter(chatListAdapter);
				}
				
			}
		};
//		Convert.chatCode=imUser.getCode();
		Convert.chatHandler=mMainHandler;
		
		new Thread(new MyThread()).start();
		
		mListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener(){
			@Override
			public void onCreateContextMenu(ContextMenu menu, View arg1,ContextMenuInfo arg2) {
				menu.setHeaderTitle("操作");
				menu.add(0, 0, 0, "复制");
				if(isMyChat){
					menu.add(0, 1, 1, "重发");
				}
				
				
			}
			
		});
		
	}
	
	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position,
			long id) {
		IMUser imUser= (IMUser)chatListAdapter.getItem(position);
		if(!"0".equals(imUser.getTitle())&&!"-1".equals(imUser.getTitle())&&!"-2".equals(imUser.getTitle())){
			isMyChat=false;
		}else{
			isMyChat=true;
		}
		return false;//此处需要注意，如果改成true，不会再次触发ListView的setOnCreateContextMenuListener事件
	}
	
	//选中菜单Item后触发
    public boolean onContextItemSelected(MenuItem item){
    	//关键代码在这里
        AdapterView.AdapterContextMenuInfo menuInfo;
        menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        IMUser imUser= (IMUser)chatListAdapter.getItem(menuInfo.position);
        if(item.getItemId()==0){
			ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			clipboard.setText(imUser.getContent());
        }else{
        	String text=say.getText().toString();
        	say.setText(Imgtools.getContent(imUser.getContent()));
        	sendSay(null);
        	say.setText(Imgtools.getContent(text));
        	say.setSelection(text.length());
        }
        //输出position
//    	Toast.makeText(main.this,String.valueOf(menuInfo.position), Toast.LENGTH_LONG).show();
    	 return super.onContextItemSelected(item); 
 
    }
	
	public void onHistory(View v){
		Intent mIntent = new Intent(this, ChatHistoryActivity.class);
//    	mIntent.putExtras(bundle);
    	Bundle bundle = new Bundle();
		bundle.putSerializable("iMUser", imUser);
		mIntent.putExtras(bundle);
//    	mIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
    	startActivityForResult(mIntent, 0);
	}
	public void sendSay(View v){
		if(say.getText().toString()==null||"".equals(say.getText().toString())){
			Toast.makeText(this, "空信息不能发送。", 8000).show();
			return;
		}
		List<NameValuePair> param=new ArrayList<NameValuePair>();
		urlSync.setPrarm(param);
		param.add(new BasicNameValuePair("fromuser",Convert.uname));
		param.add(new BasicNameValuePair("touser",imUser.getUname()));
		param.add(new BasicNameValuePair("say",say.getText().toString()));
		IMUser imUser2=new IMUser();
		imUser2.setCode(imUser.getCode()+"-"+UUID.randomUUID().toString().replaceAll("-", ""));
		 imUser2.setTitle("0");
		 imUser2.setContent(say.getText().toString());
		 imUser2.setReplyType("31");
		 imUser2.setUname(Convert.uname);
		 imUser2.setMaincode(imUser.getMaincode());
		 imUser2.setLevel("102");
		 imUser2.setFather(imUser.getCode());
//		 imUser2.setLastUpdateTime(userCursor.getString(7));
		urlSync.setImUser(imUser2);
		urlSync.setResultType("31");
		urlSync.setModth(UrlSync.POST);
		urlSync.setNotice(false);
		urlSync.setUri(GetSyncUrl.getAppUrlByCode(imUser.getMaincode())+"/SendSay");
		urlSync.setMaincode(imUser.getMaincode());
		urlSync.setSyncType(UrlSync.INFOSEND);
		urlSync.setHandler(mMainHandler);
		urlSync.setCode(imUser.getCode());
		urlSync.setToast(false);
//		urlSync.setToastContentSu("对 ["+imUser.getUname()+"] 发送的信息成功了。");
//		urlSync.setToastContentFa("对 ["+imUser.getUname()+"] 发送的信息失败了。");
		synchronized (Convert.class) {
			Convert.syncList.add(0,urlSync);
			UrlSync urlSync2=new UrlSync();
			urlSync2.setNotice(true);
			urlSync2.setUri(GetSyncUrl.getAppUrlByCode(imUser.getMaincode())+"/InfoUpdate");
			urlSync2.setMaincode(imUser.getMaincode());
			urlSync2.setSyncType(UrlSync.INFOUPDATE);
			Convert.syncList.add(0,urlSync2);
		}
//		Toast.makeText(this, "正在提交。", 4000).show();
		say.setText("");
		
		ContentValues activeuser = new ContentValues();
		activeuser.put("code",imUser2.getCode() );
		activeuser.put("maincode", imUser2.getMaincode());
		activeuser.put("username", imUser2.getUname());
		activeuser.put("content", imUser2.getContent());
		activeuser.put("title", "-2");
		activeuser.put("status", "1");
		activeuser.put("level", imUser2.getLevel());
		activeuser.put("father", imUser2.getFather());
		activeuser.put("replyType", imUser2.getReplyType());
		activeuser.put("lastUpdateTime", Convert.format1.format(new Date()));
		synchronized (InfoSync.class) {
			DBhelper.getDBHelper(this).getWritableDatabase().insert("content", null, activeuser);
		}
		new Thread(new MyThread()).start();
		
	}
	
	public void onBack(View v){
		this.setResult(RESULT_CANCELED, intent); 
		this.finish();
	}
	
	public void gotoImageGroup() {
		/* new一个Intent对象，并指定class */
		Intent intent = new Intent();
		intent.setClass(this, ImageGroup.class);
		intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);

		// /*new一个Bundle对象，并将要传递的数据传入*/
		// Bundle bundle = new Bundle();
		// bundle.putDouble("height",height);
		// bundle.putString("sex",sex);
		//
		// /*将Bundle对象assign给Intent*/
		// intent.putExtras(bundle);

		/* 调用Activity EX03_11_1 */
		startActivityForResult(intent, 0);
	}
	@Override
	public void addImg(String str) {
		String content=say.getText().toString();
		int p= say.getSelectionStart();
		say.setText(Imgtools.getContent(content.substring(0, p)+str+content.substring(p)));
		say.setSelection(p+str.length());
//		edittext.append(str);
		// TODO Auto-generated method stub
		
	}

	/* 覆盖 onActivityResult() */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
			/* 取得来自Activity2的数据，并显示于画面上 */
			Bundle bunde = data.getExtras();
			String str = bunde.getString("data");
			// double height = bunde.getDouble("height");
//			Toast.makeText(this, str, Toast.LENGTH_SHORT).show();// 显示信息;

			addImg(str);
			break;
		default:
			break;
		}
	}
	
//	@Override
//    public void onAttachedToWindow() {
//            this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
//            super.onAttachedToWindow();
//
//    }
//	@Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//            // TODO Auto-generated method stub
//            switch(keyCode) {
//            case KeyEvent.KEYCODE_HOME:
//                    goHome();
//                    break;
//            }
//            return false;
//    }
//	
//	public void goHome(){
//		Intent intent = new Intent();
//		intent.setClass(this, QQ_Main.class);
//		Bundle bundle = new Bundle();
//		bundle.putString("code",imUser.getMaincode()+"-s1");
//		intent.putExtras(bundle);
//		this.startActivity(intent); 
//		this.finish();
////		startActivityForResult(intent, 0);
//	}
	
	public void onResume() {
	    super.onResume();
	    Convert.chatCode=imUser.getCode();
		Convert.chatHandler=mMainHandler;
		new Thread(new MyThread()).start();
//	    chatListAdapter.getData();
	}
	public void onPause() {
	    super.onPause();
	    urlSync.setHandler(null);
	    Convert.chatCode=null;
		Convert.chatHandler=null;
	}
	
	public void onStop(){
		super.onStop();
		urlSync.setHandler(null);
	    Convert.chatCode=null;
		Convert.chatHandler=null;
		
	}
	
	/*
	 * 控件单击事件监听器函数
	 * */
	@Override
	public void onClick(View view){
		gotoImageGroup();
	}
	class MyThread implements Runnable{
		@Override
		  public void run() {
			Message msg=chatListHandler.obtainMessage();
			if(chatListAdapter == null&&imUser!=null){
				chatListAdapter = null;
				chatListAdapter = new ChatListAdapter(chatWindows,imUser.getCode());
				msg.arg1=2;
			}else{
				msg.arg1=1;
			}
		  
		  
		  chatListHandler.sendMessage(msg);
		  }
	}

}
